package com.android.mi_temperature2_for_dilink;

import android.app.Service;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.preference.PreferenceManager;

import com.android.mi_temperature2_for_dilink.databinding.LayoutFloatingMainNewBinding;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanAndConnectCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.socks.library.KLog;

public class MyService extends Service {
    private BleDevice connectedBleDevice;

    public MyService() {
        KLog.e();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        KLog.e();
    }

    @Override
    public IBinder onBind(Intent intent) {
        KLog.e();
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int ret = super.onStartCommand(intent, flags, startId);
        KLog.e();
        if (intent.getBooleanExtra("isBackground", false)) {
            NotificationHelper.showNotification(this);
        }
        LayoutFloatingMainNewBinding binding = LayoutFloatingMainNewBinding.inflate(LayoutInflater.from(this));
        View floating_root_view = binding.getRoot();
        BleDataHolder holder = new BleDataHolder();
        binding.setBleData(holder);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        FloatingWindowHelper helper = new FloatingWindowHelper(this);

        binding.closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                helper.removeView(floating_root_view);
                stopSelf();
            }
        });
        binding.shuShiDuTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(MyService.this, MainActivity.class);
                intent1.putExtra("fromFloating", true);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent1);
            }
        });

        String last_device_address = preferences.getString(Constants.KEY_LAST_DEVICE_ADDRESS, "");
        if (!TextUtils.isEmpty(last_device_address)) {
            int padding_left = Integer.parseInt(preferences.getString(Constants.KEY_PADDING_LEFT, "0"));
            int padding_top = Integer.parseInt(preferences.getString(Constants.KEY_PADDING_TOP, "0"));
            if (!helper.contains(floating_root_view)) {
                helper.addView(floating_root_view, padding_left, padding_top, true, false);
                BleManager.getInstance().connect(last_device_address, new BleScanAndConnectCallback() {
                    @Override
                    public void onScanFinished(BleDevice scanResult) {
                        KLog.e();
                    }

                    @Override
                    public void onStartConnect() {
                        KLog.e();
                    }

                    @Override
                    public void onConnectFail(BleDevice bleDevice, BleException exception) {
                        KLog.e();
                        Toast.makeText(MyService.this, "蓝牙连接失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                        KLog.e();
                        connectedBleDevice = bleDevice;
                        BleManager.getInstance().notify(bleDevice, UuidUtil.MAIN_DATA_SRV, UuidUtil.MAIN_DATA_CH, new BleNotifyCallback() {
                            @Override
                            public void onNotifySuccess() {
                                KLog.e();
                            }

                            @Override
                            public void onNotifyFailure(BleException exception) {
                                KLog.e(exception.toString());
                            }

                            @Override
                            public void onCharacteristicChanged(byte[] data) {
                                KLog.e();
                                int[] parseData = MainActivity.parseData(data);
                                holder.setTemperature(parseData[0] + "");
                                holder.setHumidity(parseData[1] + "");
                                holder.setVoltage(parseData[2] + "");
                                holder.setShuShiDu(parseData[0], parseData[1]);
                                binding.setBleData(holder);
                            }
                        });
                    }

                    @Override
                    public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                        KLog.e();
                    }

                    @Override
                    public void onScanStarted(boolean success) {
                        KLog.e();
                    }

                    @Override
                    public void onScanning(BleDevice bleDevice) {
                        KLog.e();
                    }
                });
            }

        }
        return ret;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        KLog.e();
        BleManager.getInstance().stopNotify(connectedBleDevice, UuidUtil.MAIN_DATA_SRV, UuidUtil.MAIN_DATA_CH);
//        BleManager.getInstance().disconnect(connectedBleDevice);
//        BleManager.getInstance().destroy();
    }
}